/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */
package com.ykht.proj.coupon.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ykht.proj.admin.api.feign.RemoteUserService;
import com.ykht.proj.admin.api.vo.UserVO;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.common.security.util.SecurityUtils;
import com.ykht.proj.coupon.Enum.*;
import com.ykht.proj.coupon.entity.*;
import com.ykht.proj.coupon.mapper.*;
import com.ykht.proj.coupon.service.*;
import com.ykht.proj.coupon.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * cms资讯表
 *
 * @author proj code generator
 * @date 2021-02-01 16:22:52
 */
@Slf4j
@Service
@Transactional
public class FxCmsInfoServiceImpl extends ServiceImpl<FxCmsInfoMapper, FxCmsInfo> implements FxCmsInfoService {

	@Resource
	private CnCouponLogMapper cnCouponLogMapper;
	@Resource
	private FxCmsTagMapper fxCmsTagMapper;
	@Resource
	private CnCouponService cnCouponService;
	@Resource
	private FxFavourService fxFavourService;
	@Resource
	private FxFavourMapper fxFavourMapper;
	@Resource
	private FxForwardMapper fxForwardMapper;
	@Resource
	private CnShopMapper cnShopMapper;
	@Resource
	private RemoteUserService remoteUserService;
	@Resource
	private FxCmsColumnRelationService fxCmsColumnRelationService;
	@Resource
	private FxCmsInfoMapper fxCmsInfoMapper;
	@Autowired
	private FxConfBrandPersonService fxConfBrandPersonService;


	@Override
	public IPage<FxCmsInfoVO> queryByPage(Page page, FxCmsInfoVO fxCmsInfoVO) {
		IPage<FxCmsInfo> iPage = new Page<>(page.getCurrent(),page.getSize());
		IPage<FxCmsInfoVO> result = this.getBaseMapper().selectValueByPage(iPage, fxCmsInfoVO);
		for (FxCmsInfoVO record : result.getRecords()) {
			if(record.getStatus().equals(CmsTypeEnum.CMS_TYPE_1.getValue())){
				record.setStatusName(CmsTypeEnum.CMS_TYPE_1.getDesc());
				record.setPostStatusName(PostStatusEnum.POST_STATUS_1.getDesc());
			}else if(record.getStatus().equals(CmsTypeEnum.CMS_TYPE_2.getValue())){
				record.setStatusName(CmsTypeEnum.CMS_TYPE_2.getDesc());
				record.setPostStatusName(PostStatusEnum.POST_STATUS_2.getDesc());
			}
			else if(record.getStatus().equals(CmsTypeEnum.CMS_TYPE_3.getValue())){
				record.setStatusName(CmsTypeEnum.CMS_TYPE_3.getDesc());
				record.setPostStatusName(PostStatusEnum.POST_STATUS_3.getDesc());
			}
			else if(record.getStatus().equals(CmsTypeEnum.CMS_TYPE_4.getValue())){
				record.setStatusName(CmsTypeEnum.CMS_TYPE_4.getDesc());
				record.setPostStatusName(PostStatusEnum.POST_STATUS_4.getDesc());
			}
			else if(record.getStatus().equals(CmsTypeEnum.CMS_TYPE_5.getValue())){
				record.setStatusName(CmsTypeEnum.CMS_TYPE_5.getDesc());
				record.setPostStatusName(PostStatusEnum.POST_STATUS_5.getDesc());
			}
			else if(record.getStatus().equals(CmsTypeEnum.CMS_TYPE_6.getValue())){
				record.setStatusName(CmsTypeEnum.CMS_TYPE_6.getDesc());
				record.setPostStatusName(PostStatusEnum.POST_STATUS_6.getDesc());
			}
			else if(record.getStatus().equals(CmsTypeEnum.CMS_TYPE_7.getValue())){
				record.setStatusName(CmsTypeEnum.CMS_TYPE_7.getDesc());
				record.setPostStatusName(PostStatusEnum.POST_STATUS_7.getDesc());
			}
		}
		return result;
	}

    @Override
    public void updateValueById(FxCmsInfo fxCmsInfo) {
//		/*如果已发布就下架*/
//		if(fxCmsInfo.getStatus().equals(auditStatus.STATUS_5.getValue())){
//			fxCmsInfo.setStatus(auditStatus.STATUS_7.getValue());
//		}
//		/*如果提交就审核*/
//		else if(fxCmsInfo.getStatus().equals(auditStatus.STATUS_3.getValue())){
//			fxCmsInfo.setStatus(auditStatus.STATUS_4.getValue());
//		}
//		/*如果审核就发布*/
//		else if(fxCmsInfo.getStatus().equals(auditStatus.STATUS_4.getValue())){
//			fxCmsInfo.setStatus(auditStatus.STATUS_5.getValue());
//		}
//		/*如果定时发布就审核 此时审核是被禁用状态*/
//		else if(fxCmsInfo.getStatus().equals(auditStatus.STATUS_6.getValue())){
//			fxCmsInfo.setStatus(auditStatus.STATUS_4.getValue());
//		}
//		/*如果下架就审核*/
//		else if(fxCmsInfo.getStatus().equals(auditStatus.STATUS_7.getValue())){
//			fxCmsInfo.setStatus(auditStatus.STATUS_4.getValue());
//		}
		fxCmsInfo.setPushTime(LocalDateTime.now());
		this.baseMapper.updateById(fxCmsInfo);
    }

	@Override
	public FxCmsInfoVO findById(Long id) {
		FxCmsInfoVO fxCmsInfoVO = this.baseMapper.findById(id);
		if(fxCmsInfoVO.getStatus().equals(CmsTypeEnum.CMS_TYPE_1.getValue())){
			fxCmsInfoVO.setStatusName(CmsTypeEnum.CMS_TYPE_1.getDesc());
		}else if(fxCmsInfoVO.getStatus().equals(CmsTypeEnum.CMS_TYPE_2.getValue())){
			fxCmsInfoVO.setStatusName(CmsTypeEnum.CMS_TYPE_2.getDesc());
		}
		else if(fxCmsInfoVO.getStatus().equals(CmsTypeEnum.CMS_TYPE_3.getValue())){
			fxCmsInfoVO.setStatusName(CmsTypeEnum.CMS_TYPE_3.getDesc());
		}
		else if(fxCmsInfoVO.getStatus().equals(CmsTypeEnum.CMS_TYPE_4.getValue())){
			fxCmsInfoVO.setStatusName(CmsTypeEnum.CMS_TYPE_4.getDesc());
		}
		else if(fxCmsInfoVO.getStatus().equals(CmsTypeEnum.CMS_TYPE_5.getValue())){
			fxCmsInfoVO.setStatusName(CmsTypeEnum.CMS_TYPE_5.getDesc());
		}
		else if(fxCmsInfoVO.getStatus().equals(CmsTypeEnum.CMS_TYPE_6.getValue())){
			fxCmsInfoVO.setStatusName(CmsTypeEnum.CMS_TYPE_6.getDesc());
		}
		else if(fxCmsInfoVO.getStatus().equals(CmsTypeEnum.CMS_TYPE_7.getValue())){
			fxCmsInfoVO.setStatusName(CmsTypeEnum.CMS_TYPE_7.getDesc());
		}
		UserVO byIdUser = remoteUserService.getByIdUser(fxCmsInfoVO.getCreateUser());
		fxCmsInfoVO.setUserName(byIdUser.getUsername());
//		R userExt = cnUserExtService.getUserExt(LookRoleTypeEnum.LOOK_ROLE_TYPE_2.getValue(), fxCmsInfoVO.getCreateUser());
		/*获取优惠券集合*/
		if(fxCmsInfoVO.getCouponId()!=null&&!"".equals(fxCmsInfoVO.getCouponId())){
			String[] couponArray = fxCmsInfoVO.getCouponId().split(",");
			List<CnCoupon> cnCouponArraylist = new ArrayList<>();
				for (String cnCoupon : couponArray) {
					cnCouponArraylist.add(cnCouponLogMapper.findById(Long.parseLong(cnCoupon)));
				}
		fxCmsInfoVO.setCouponList(cnCouponArraylist);
		}
		/*获取标签集合*/
		if(fxCmsInfoVO.getTags()!=null&&!"".equals(fxCmsInfoVO.getTags())){
			String[] tagArray = fxCmsInfoVO.getTags().split(",");
			List<FxCmsTag> fxCmsTagList = new ArrayList<>();
			for (String fxCmsTag : tagArray) {
				fxCmsTagList.add(fxCmsTagMapper.findById(Long.parseLong(fxCmsTag)));
			}
		fxCmsInfoVO.setTagList(fxCmsTagList);
		}
		return fxCmsInfoVO;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delById(Long id) {
		this.baseMapper.delById(id);
		// 删除文章的栏目
		fxCmsColumnRelationService.remove(Wrappers.lambdaQuery(FxCmsColumnRelation.class)
				.eq(FxCmsColumnRelation::getCmsId, id));
	}

	@Override
	public void updateStatus(String ids, Integer status,Long userId) {
		String[] arr = ids.split(",");
		for (String s : arr) {
			FxCmsInfo fxCmsInfo = new FxCmsInfo();
			fxCmsInfo.setId(Long.parseLong(s));
			fxCmsInfo.setStatus(status);
			if(status==CmsTypeEnum.CMS_TYPE_3.getValue()){
				fxCmsInfo.setPushTime(LocalDateTime.now());
			}
			fxCmsInfo.setUpdateUser(userId);
			fxCmsInfo.setUpdateTime(LocalDateTime.now());
			this.baseMapper.updateById(fxCmsInfo);
		}
	}

	@Override
	public FxCmsInfoCount queryCount(FxCmsInfoVO fxCmsInfoVO) {
		FxCmsInfoCount cmsInfoCount = new FxCmsInfoCount();
		/*置顶数*/
		cmsInfoCount.setStickCount(this.baseMapper.stickCount(AuditStatus.STATUS_STICK_1.getValue(),fxCmsInfoVO));
		/*文章计数、视频计数*/
		cmsInfoCount.setTextCount(this.baseMapper.infomationTypeCount(AuditStatus.STATUS_INFORMATION_TYPE_0.getValue(),fxCmsInfoVO));
		cmsInfoCount.setVideoCount(this.baseMapper.infomationTypeCount(AuditStatus.STATUS_INFORMATION_TYPE_1.getValue(),fxCmsInfoVO));
		/*状态计数 */
		/*提交计数*/
		cmsInfoCount.setSubmitCount(this.baseMapper.statusCount(AuditStatus.STATUS_CMS_INFO_4.getValue(),fxCmsInfoVO));
		/*审核计数*/
		cmsInfoCount.setCheckCount(this.baseMapper.statusCount(AuditStatus.STATUS_CMS_INFO_5.getValue(),fxCmsInfoVO));
		/*审核失败计数*/
		cmsInfoCount.setCheckOutCount(this.baseMapper.statusCount(AuditStatus.STATUS_CMS_INFO_6.getValue(),fxCmsInfoVO));
		/*发布计数*/
		cmsInfoCount.setIssueCount(this.baseMapper.statusCount(AuditStatus.STATUS_CMS_INFO_3.getValue(),fxCmsInfoVO));
		/*定时发布计数*/
		cmsInfoCount.setRealTimeIssueCount(this.baseMapper.statusCount(AuditStatus.STATUS_CMS_INFO_2.getValue(),fxCmsInfoVO));
		/*下架计数*/
		cmsInfoCount.setSoldOutCount(this.baseMapper.statusCount(AuditStatus.STATUS_CMS_INFO_7.getValue(),fxCmsInfoVO));
		/*全部计数*/
		cmsInfoCount.setAllCount(this.baseMapper.allCount(fxCmsInfoVO));
//		/*文章草稿计数*/
		cmsInfoCount.setTextDraftCount(this.baseMapper.textDraftCoun(fxCmsInfoVO));
//		/*视频草稿计数*/
		cmsInfoCount.setVideoDraftCount(this.baseMapper.videoDraftCount(fxCmsInfoVO));
		/*所有草稿计数*/
		cmsInfoCount.setDraftCount(this.baseMapper.draftCount(fxCmsInfoVO));

		return cmsInfoCount;
	}


	@Override
	public R<CmsInfoTemplate> getCmsInfoTemplateById(Long id, Integer addCouponFlag, Long waiterId, BaseLonLat lonLat) {

		Long loginId = SecurityUtils.getPersonId();
		CmsInfoTemplate cmsInfoTemplate = new CmsInfoTemplate();
		FxCmsInfo cmsInfo = this.getOne(Wrappers.lambdaQuery(FxCmsInfo.class)
				.eq(FxCmsInfo::getId,id).eq(FxCmsInfo::getStatus, CmsTypeEnum.CMS_TYPE_3.getValue()));
		if (cmsInfo==null) return R.failed("文章不存在");
		cmsInfoTemplate.setCmsInfo(cmsInfo);

		CnBrand brand = new CnBrand().selectOne(Wrappers.lambdaQuery(CnBrand.class).select(CnBrand::getId,CnBrand::getBrandName,CnBrand::getLogoUrl).eq(CnBrand::getId,cmsInfo.getBrandId()));

		//分销“赚”字
		cmsInfoTemplate.setFxFlag(fxConfBrandPersonService.fxFlag(brand.getId()));
		//品牌资讯的个数
		Integer brandCmsCount = this.count(Wrappers.lambdaQuery(FxCmsInfo.class).eq(FxCmsInfo::getBrandId,cmsInfo.getBrandId()).eq(FxCmsInfo::getStatus,CmsTypeEnum.CMS_TYPE_3.getValue()));
		cmsInfoTemplate.setBrandCmsCount(brandCmsCount);

		Integer care = new CnCare().selectCount(Wrappers.lambdaQuery(CnCare.class).eq(CnCare::getTgtId, cmsInfo.getBrandId()).eq(CnCare::getPerId, loginId).eq(CnCare::getType, 0));
		cmsInfoTemplate.setCareFlag(care>0 ? 0 : 1);

		cmsInfoTemplate.setBrand(brand);
		FxWaiterExt fxWaiterExt = null;
		if (waiterId!=null){
			fxWaiterExt = new FxWaiterExt().selectById(waiterId);
			log.info("服务员信息,{}",fxWaiterExt);
			if (fxWaiterExt!=null&&fxWaiterExt.getShopId()!=null){
				CnShop cnShop = new CnShop().selectById(fxWaiterExt.getShopId());
				log.info("门店信息,{}",cnShop);
				if (cnShop!=null){
					cmsInfoTemplate.setShop(cnShop);
					cmsInfoTemplate.setPhone(cnShop.getPhone());
				}
			}
		}
		//点赞
		FxFavour favour = fxFavourService.getOne(Wrappers.lambdaQuery(FxFavour.class)
				.eq(FxFavour::getArticleId,id).eq(FxFavour::getPerId,loginId).eq(FxFavour::getStatus,0));//是否点过赞
		cmsInfoTemplate.setFavourFlag(favour!=null?0:1);
		//点赞量
		cmsInfoTemplate.setReadCount(fxFavourMapper.getReadCount(id));

		if (StringUtils.isNotEmpty(cmsInfo.getCouponId()) ) {
			String[] ids = cmsInfo.getCouponId().split(",");
			if (ids.length!=0 && addCouponFlag!=null&&0==addCouponFlag){
				List<CnCoupon> list = cnCouponService.list(Wrappers.lambdaQuery(CnCoupon.class).in(CnCoupon::getId,Arrays.asList(ids)).eq(CnCoupon::getStatus, StatusEnum.normal.getValue()));//所有优惠券
				//可用的优惠券列表
				List<Long> logList = cnCouponLogMapper.selectList(Wrappers.lambdaQuery(CnCouponLog.class)
						.eq(CnCouponLog::getRecipientId,loginId).eq(CnCouponLog::getStatus,0))
						.stream().map(CnCouponLog::getCouponId).collect(Collectors.toList());
				list = list.stream().filter(o->logList.contains(o.getId())!=true).limit(3).collect(Collectors.toList());//去除领取过的优惠券
				cmsInfoTemplate.setCouponList(list);
			}
		}

		//品牌内最近的门店
		if (BeanUtil.isNotEmpty(lonLat)) {
			Long shopId = cnShopMapper.nearShopIdByBrandIdAndLanlon(brand.getId(),lonLat);
			if (shopId!=null){
				AboutShopVo nearShop = cnShopMapper.aboutShop(new AboutShopReq(shopId,lonLat));
				cmsInfoTemplate.setNearShop(nearShop);
			}
		}
		//每个用户看到的评论规则，审核通过的数量加上自己评论未审核的数量
		Integer num = new FxComment().selectCount(Wrappers.lambdaQuery(FxComment.class)
				.eq(FxComment::getCmsId, id).eq(FxComment::getPublishId, SecurityUtils.getPersonId()).eq(FxComment::getStatus, 1));
		cmsInfo.setCommentTimes(cmsInfo.getCommentTimes()+num);


		//吃哈哈二期吃货攻略
		//兴趣标签次数即用户阅读过所有的内容文章中标签计数统合后，每篇文章仅的标签仅计一次;
		if (StringUtils.isNotBlank(cmsInfo.getTags())){
			List<String> tags = Arrays.asList(cmsInfo.getTags().split(","));
			List<Long> ids = new FxPersonBrowseLabel().selectList(Wrappers.lambdaQuery(FxPersonBrowseLabel.class).select(FxPersonBrowseLabel::getLabelId).in(FxPersonBrowseLabel::getLabelId, tags)).stream().map(FxPersonBrowseLabel::getLabelId).collect(Collectors.toList());

			FxWaiterExt finalFxWaiterExt = fxWaiterExt;
			List<FxPersonBrowseLabel> collect = tags.stream().filter(o -> ids.contains(o)).map(o -> {
				FxPersonBrowseLabel label = new FxPersonBrowseLabel();
				if (finalFxWaiterExt !=null) {
					label.setCompanyId(finalFxWaiterExt.getCompanyId());
					label.setBrandId(finalFxWaiterExt.getBrandId());
					label.setWaiterId(finalFxWaiterExt.getId());
				}
				CnLabel cnLabel = new CnLabel().selectById(o);
				if (cnLabel != null) {
					label.setLabelName(cnLabel.getName());
				}
				label.setLabelId(Long.parseLong(o));
				label.setCreateTime(LocalDateTime.now());
				label.setCreateUser(SecurityUtils.getPersonId());
				return label;
			}).collect(Collectors.toList());
			fxPersonBrowseLabelService.saveOrUpdateBatch(collect);
		}
		return R.ok(cmsInfoTemplate);
	}
	@Resource
	private FxPersonBrowseLabelService fxPersonBrowseLabelService;

    @Override
    public IPage<FxCmsInfoVO> getBrandInformation(Page page,FxCmsInfoVO fxCmsInfoVO) {
		/*
		* 品牌时讯的文章按照文章排序规则  置顶排序+浏览量+最新文章 分页并每次获取8条
		* */
		return this.baseMapper.getBrandInformation(page,fxCmsInfoVO);
    }

	@Override
	public IPage<FxCmsInfoVO> getWonderfulRecommend(Page page,FxCmsInfoVO fxCmsInfoVO) {
		/*精彩推荐的内容展示规则
		取当前品牌文章的浏览量前五篇和所有文章（除当前品牌文章）的浏览量前五篇加起来共10篇;
		按照浏览量对此10篇文章倒叙排列展示
		*/
		long current = 0L;
		long size = page.getSize();
		List<FxCmsInfoVO> topBook= this.baseMapper.getTopBook(current,size/2,fxCmsInfoVO.getBrandId(),fxCmsInfoVO.getId());
//		size = 10 - topBook.size();
		List<FxCmsInfoVO> bottomBook= this.baseMapper.getBottomBook(current,size/2,fxCmsInfoVO.getBrandId());
		topBook.addAll(bottomBook);
		topBook.stream()
				.forEach(result->result.setReadNum(result.getBaseReadNum()+result.getReadNum()));
		topBook = topBook.stream()
				.sorted(Comparator.comparing(FxCmsInfoVO::getReadNum).reversed())
				.collect(Collectors.toList());
		IPage<FxCmsInfoVO> fxCmsInfoIPage = new Page(page.getCurrent(),page.getSize());
		fxCmsInfoIPage.setRecords(topBook);
		return fxCmsInfoIPage;
	}

	@Override
	public Object addReadCount(FxCmsInfo fxCmsInfo) {
		/*
		* 首先获取当前文章的阅读量
		* 添加阅读量并保存
		* */
		FxCmsInfo resultFxCmsInfo = this.baseMapper.queryById(fxCmsInfo);
		resultFxCmsInfo.setReadNum(resultFxCmsInfo.getReadNum()+1);
		this.baseMapper.updateReadCount(resultFxCmsInfo);
		return null;
	}

    @Override
    public Map<String, List<FxCmsInfoVO>> queryByBrandId(FxWaiterExt waiterExt) {
		Map<String, List<FxCmsInfoVO>> listMap = new HashMap<String, List<FxCmsInfoVO>>();
		/*首先获取全部文章*/
		List<FxCmsInfoVO> allCmsInfo = this.baseMapper.queryAllCmsInfo(waiterExt);
		Long userId = SecurityUtils.getUserId();
		for (FxCmsInfoVO fxCmsInfoVO : allCmsInfo) {
			Integer count = fxForwardMapper.selectCount(Wrappers.lambdaQuery(FxForward.class)
					.eq(FxForward::getCreateUser, userId)
					.eq(FxForward::getArticleId, fxCmsInfoVO.getId())
					.eq(FxForward::getDelFlag,0)
			);
			fxCmsInfoVO.setMyForwardCount(count);
		}
		listMap.put("A",allCmsInfo);
		List<Integer> unfinished = fxForwardMapper.queryByUserId(waiterExt);
		unfinished = unfinished.stream()
				.filter(Objects::nonNull)
				.distinct()
				.collect(Collectors.toList());
		if(unfinished.size()>0){
			/*获取未完成转发的文章*/
			List<FxCmsInfoVO> unfinishedCmsInfo = this.baseMapper.queryUnfinished(unfinished,waiterExt);
			for (FxCmsInfoVO fxCmsInfoVO : unfinishedCmsInfo) {
				Integer count = fxForwardMapper.selectCount(Wrappers.lambdaQuery(FxForward.class)
						.eq(FxForward::getCreateUser, userId)
						.eq(FxForward::getArticleId, fxCmsInfoVO.getId())
						.eq(FxForward::getDelFlag,0)
				);
				fxCmsInfoVO.setMyForwardCount(count);
			}
			listMap.put("B",unfinishedCmsInfo);
			/*获取完成转发的文章*/
			List<FxCmsInfoVO> finishedCmsInfo = this.baseMapper.queryFinished(unfinished,waiterExt);
			for (FxCmsInfoVO fxCmsInfoVO : finishedCmsInfo) {
				Integer count = fxForwardMapper.selectCount(Wrappers.lambdaQuery(FxForward.class)
						.eq(FxForward::getCreateUser, userId)
						.eq(FxForward::getArticleId, fxCmsInfoVO.getId())
						.eq(FxForward::getDelFlag,0)
				);
				fxCmsInfoVO.setMyForwardCount(count);
			}
			listMap.put("C",finishedCmsInfo);
		}else {
			listMap.put("B",allCmsInfo);
			listMap.put("C",null);
		}
		return listMap;
    }

	@Override
	public void addForward(Long articleId) {
		/*
		* 先获取之前的转发次数
		* 转发此处加1并回存表
		* */
		Integer forWardCount = this.baseMapper.queryForward(articleId);
		FxCmsInfo fxCmsInfo = new FxCmsInfo();
		fxCmsInfo.setId(articleId);
		fxCmsInfo.setForwardTime(forWardCount+1);
		this.updateById(fxCmsInfo);
	}

	@Override
	public R<CmsInfoTemplate> getCmsInfoTemplateById_B(Long id) {
		CmsInfoTemplate cmsInfoTemplate = new CmsInfoTemplate();
		FxCmsInfo cmsInfo = this.getOne(Wrappers.lambdaQuery(FxCmsInfo.class)
				.eq(FxCmsInfo::getId,id).eq(FxCmsInfo::getStatus, CmsTypeEnum.CMS_TYPE_3.getValue()));
		if (cmsInfo==null) return R.failed("文章不存在");
		cmsInfoTemplate.setCmsInfo(cmsInfo);

		CnBrand brand = new CnBrand();
		brand.setId(cmsInfo.getBrandId());
		brand =brand.selectById();
		cmsInfoTemplate.setBrand(brand);
		//点赞量
		cmsInfoTemplate.setReadCount(fxFavourMapper.getReadCount(id));

		if (StringUtils.isNotEmpty(cmsInfo.getCouponId()) ) {
			String[] ids = cmsInfo.getCouponId().split(",");
			if (ids.length==0) return R.ok(cmsInfoTemplate);

			List<CnCoupon> list = cnCouponService.listByIds(Arrays.asList(ids));//所有优惠券
			cmsInfoTemplate.setCouponList(list);
		}
		return R.ok(cmsInfoTemplate);
	}

	/**
	 * 新增cms资讯表
	 *
	 * @param fxCmsInfoVO cms资讯表
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R saveBatchFxCmsInfo(FxCmsInfoVO fxCmsInfoVO) {
		List<FxCmsInfo> cmsInfoList = new ArrayList<>();
		if (fxCmsInfoVO.getBrandList().size() > 0) {
			if (null != fxCmsInfoVO.getCouponIdList() && fxCmsInfoVO.getCouponIdList().size() > 0) {
				log.info("获取选择的所有的优惠券并更具品牌ID分组:{}", fxCmsInfoVO.getCouponIdList());
				List<CnCoupon> cnCouponList = new CnCoupon().selectList(Wrappers.lambdaQuery(CnCoupon.class)
						.in(CnCoupon::getId, fxCmsInfoVO.getCouponIdList()));
				Map<Long, List<CnCoupon>> collect = cnCouponList.stream().collect(Collectors.groupingBy(o -> o.getBrandId()));
				log.info("给文章的品牌添加优惠券:{}", collect);
				fxCmsInfoVO.getBrandList().stream().forEach(itme -> {
					fxCmsInfoVO.setBrandId(itme.getBrandId());
					fxCmsInfoVO.setCompanyId(itme.getCompanyId());
					List<CnCoupon> couponList = collect.get(itme.getBrandId());
					if (null != couponList && couponList.size() > 0) {
						List<String> longList = couponList.stream().map(coupon -> String.valueOf(coupon.getId())).collect(Collectors.toList());
						fxCmsInfoVO.setCouponId(String.join(",", longList));
					} else {
						fxCmsInfoVO.setCouponId(null);
					}
					cmsInfoList.add(BeanUtil.toBean(fxCmsInfoVO, FxCmsInfo.class));
				});
			} else {
				fxCmsInfoVO.getBrandList().stream().forEach(itme -> {
					fxCmsInfoVO.setBrandId(itme.getBrandId());
					fxCmsInfoVO.setCompanyId(itme.getCompanyId());
					cmsInfoList.add(BeanUtil.toBean(fxCmsInfoVO, FxCmsInfo.class));
				});
			}
			log.info("批量添加文章:{}", cmsInfoList);
			this.saveBatch(cmsInfoList);
			log.info("给批量添加的文章添加栏目:{}", fxCmsInfoVO.getColumnIdList());
			cmsInfoList.stream().forEach(itme ->{
				List<FxCmsColumnRelation> cmsColumnRelationListList = new ArrayList<>();
				fxCmsInfoVO.getColumnIdList().stream().forEach(columnId ->{
					FxCmsColumnRelation fxCmsColumnRelation = new FxCmsColumnRelation();
					fxCmsColumnRelation.setCmsId(itme.getId());
					fxCmsColumnRelation.setColId(columnId);
					fxCmsColumnRelation.setCreateTime(LocalDateTime.now());
					fxCmsColumnRelation.setCreateUser(SecurityUtils.getUserId());
					cmsColumnRelationListList.add(fxCmsColumnRelation);
				});
				fxCmsColumnRelationService.saveBatch(cmsColumnRelationListList);
			});

		}/* else {
			fxCmsInfoVO.setBrandId(fxCmsInfoVO.getBrandList().get(0).getBrandId());
			fxCmsInfoVO.setCompanyId(fxCmsInfoVO.getBrandList().get(0).getCompanyId());
			fxCmsInfoVO.setCouponId(String.join(",", fxCmsInfoVO.getCouponIdList().stream().map(o -> o.toString()).collect(Collectors.toList())));
			return R.ok(this.save(BeanUtil.toBean(fxCmsInfoVO, FxCmsInfo.class)));
		}*/
		return R.ok();
	}

	/**
	 * 取10公里以内的门店的对应品牌
	 *
	 * @param page
	 * @param req
	 * @return
	 */
	@Override
	public R<Page<CmsTemplateCover>> home(Page page, CmsTemplateCoverReq req) {
//		List<Long> brandIds = cnShopMapper.brandIdByDistant(req.getLonLat(),req.getDistance());
//		if (brandIds.size()==0) return R.ok(page);
//		req.setBrandIds(brandIds);
		Integer num = new FxCmsColumn().selectCount(Wrappers.lambdaQuery(FxCmsColumn.class).eq(FxCmsColumn::getDefFlag, 1).eq(FxCmsColumn::getId, req.getColumId()));
		req.setRelationFlag(num>0||req.getColumId()==null?1:0);
		page = fxCmsInfoMapper.homeCmsCover(page, req);
		return R.ok(page);
	}

	@Override
	public Page<PushCms4C> pushCmsPage(Page<PushCms4C> page, BaseLonLat lonLat) {
		page = fxCmsInfoMapper.pushCmsPage(page,lonLat);
		//品牌内最近的门店
		if (BeanUtil.isNotEmpty(lonLat)) {
			Set<Long> brandIds = page.getRecords()
					.stream().filter(o->o.getBrandId() != null).map(PushCms4C::getBrandId).collect(Collectors.toSet());
			Map<Long, CnShopDisVo> brandMap = cnShopMapper.nearShopIdByBrandIdsAndLanlon(brandIds, lonLat)
					.stream().collect(Collectors.toMap(CnShopDisVo::getBrandId, Function.identity(), (key1, key2) -> key2));
			page.getRecords().stream().forEach(o->o.setNearShop(brandMap.get(o.getBrandId())));
		}
		return page;
	}


	/**
	 * 通过id查询cms资讯表（文章）
	 *
	 * @param id
	 * @return
	 */
	@Override
	public FxCmsInfoVO getByIdFxCmsInfoVO(Long id) {
		FxCmsInfoVO fxCmsInfoVO = cnCouponLogMapper.getByIdFxCmsInfoVO(id);
		if(fxCmsInfoVO.getCouponId() != null && !"".equals(fxCmsInfoVO.getCouponId())){
			String[] couponArray = fxCmsInfoVO.getCouponId().split(",");
			List<CnCoupon> cnCouponArraylist = new ArrayList<>();
			for (String cnCoupon : couponArray) {
				cnCouponArraylist.add(cnCouponLogMapper.findById(Long.parseLong(cnCoupon)));
			}
			fxCmsInfoVO.setCouponList(cnCouponArraylist);
		}
		List<FxCmsColumnRelation> selectList = new FxCmsColumnRelation().selectList(Wrappers.lambdaQuery(FxCmsColumnRelation.class)
				.eq(FxCmsColumnRelation::getCmsId, id));
		fxCmsInfoVO.setColumnIdList(selectList.stream().map(FxCmsColumnRelation::getColId).collect(Collectors.toList()));
		return fxCmsInfoVO;
	}


	/**
	 * 修改cms资讯表
	 *
	 * @param fxCmsInfoVO
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateFxCmsInfo(FxCmsInfoVO fxCmsInfoVO) {
		// 修改文章
//		fxCmsInfoVO.setCouponId(String.join(",", fxCmsInfoVO.getCouponIdList().stream().map(o -> o.toString()).collect(Collectors.toList())));
		fxCmsInfoVO.getBrandList().stream().forEach(itme -> {
			fxCmsInfoVO.setBrandId(itme.getBrandId());
			fxCmsInfoVO.setCompanyId(itme.getCompanyId());
		});
		this.updateById(BeanUtil.toBean(fxCmsInfoVO, FxCmsInfo.class));
		if (null != fxCmsInfoVO.getColumnIdList() && fxCmsInfoVO.getColumnIdList().size() > 0){
			// 删除文章的栏目
			fxCmsColumnRelationService.remove(Wrappers.lambdaQuery(FxCmsColumnRelation.class)
					.eq(FxCmsColumnRelation::getCmsId, fxCmsInfoVO.getId()));
			// 添加新的文章栏目
			List<FxCmsColumnRelation> cmsColumnRelationListList = new ArrayList<>();
			fxCmsInfoVO.getColumnIdList().stream().forEach(columnId ->{
				FxCmsColumnRelation fxCmsColumnRelation = new FxCmsColumnRelation();
				fxCmsColumnRelation.setCmsId(fxCmsInfoVO.getId());
				fxCmsColumnRelation.setColId(columnId);
				fxCmsColumnRelation.setCreateTime(LocalDateTime.now());
				fxCmsColumnRelation.setCreateUser(SecurityUtils.getUserId());
				cmsColumnRelationListList.add(fxCmsColumnRelation);
			});
			fxCmsColumnRelationService.saveBatch(cmsColumnRelationListList);
		}

	}

	/**
	 * 添加cms资讯表（推荐值）
	 *
	 * @param fxCmsInfo
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void addRecommend(FxCmsInfo fxCmsInfo) {
		boolean update = this.updateById(fxCmsInfo);
		FxCmsInfo cmsInfo = this.getById(fxCmsInfo.getId());
		FxCmsRecommend fxCmsRecommend = new FxCmsRecommend();
		fxCmsRecommend.setCompanyId(cmsInfo.getCompanyId());
		fxCmsRecommend.setBrandId(cmsInfo.getBrandId());
		fxCmsRecommend.setCmsId(cmsInfo.getId());
		fxCmsRecommend.setStatus(cmsInfo.getRecommendStatus());
		fxCmsRecommend.setRecommendValue(cmsInfo.getRecommendValue());
		fxCmsRecommend.setStartTime(cmsInfo.getRecommendStartTime());
		fxCmsRecommend.setEndTime(cmsInfo.getRecommendEndTime());
		fxCmsRecommend.setCreateUser(SecurityUtils.getUserId());
		fxCmsRecommend.setCreateTime(LocalDateTime.now());
		boolean insert = fxCmsRecommend.insert();
	}

	/**
	 * 根据品牌ID查询 品牌时讯
	 *
	 * @param page
	 * @param fxCmsInfoVO
	 * @return
	 */
	@Override
	public IPage<FxCmsInfoVO> getBrandCmsPage(Page page, FxCmsInfoVO fxCmsInfoVO) {
		return fxCmsInfoMapper.getBrandCmsPage(page, fxCmsInfoVO);
	}

	/**
	 * S-01首页（文章搜索（精选内容））
	 *
	 * @param page        分页
	 * @param homePageSearch 条件
	 * @return
	 */
	@Override
	public IPage<FxCmsInfoVO> getCmsRecommendPage(Page page, HomePageSearch homePageSearch) {
		return fxCmsInfoMapper.getCmsRecommendPage(page, homePageSearch);
	}

	/**
	 * 根据品牌切换视频
	 *
	 * @param page        分页
	 * @param fxCmsInfoVO 条件
	 * @return
	 */
	@Override
	public IPage<FxCmsInfoVO> getBrandSwitchVideoPage(Page page, FxCmsInfoVO fxCmsInfoVO) {
		return fxCmsInfoMapper.getBrandSwitchVideoPage(page, fxCmsInfoVO);
	}

	/**
	 * 根据首页切换视频
	 *
	 * @param page        分页
	 * @param fxCmsInfoVO 条件
	 * @return
	 */
	@Override
	public IPage<FxCmsInfoVO> getHomeSwitchVideoPage(Page page, FxCmsInfoVO fxCmsInfoVO) {
		return fxCmsInfoMapper.getHomeSwitchVideoPage(page, fxCmsInfoVO);
	}

	/**
	 * 批量修改cms资讯 栏目
	 *
	 * @param idList       文章id集合
	 * @param columnIdList 栏目id集合
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateColumnId(List<Long> idList, List<Long> columnIdList) {
		// 删除文章的栏目
		fxCmsColumnRelationService.remove(Wrappers.lambdaQuery(FxCmsColumnRelation.class)
				.in(FxCmsColumnRelation::getCmsId, idList));
		// 添加新的文章栏目
		List<FxCmsColumnRelation> cmsColumnRelationListList = new ArrayList<>();
		idList.stream().forEach(itme ->{
			columnIdList.stream().forEach(columnId ->{
				FxCmsColumnRelation fxCmsColumnRelation = new FxCmsColumnRelation();
				fxCmsColumnRelation.setCmsId(itme);
				fxCmsColumnRelation.setColId(columnId);
				fxCmsColumnRelation.setCreateTime(LocalDateTime.now());
				fxCmsColumnRelation.setCreateUser(SecurityUtils.getUserId());
				cmsColumnRelationListList.add(fxCmsColumnRelation);
			});
		});
		fxCmsColumnRelationService.saveBatch(cmsColumnRelationListList);
	}


}
